import api from './api';
import store from './reducers';
import req from './utils/req';
let device_id = localStorage.getItem('uniqueId');
if (!device_id) {
  device_id = new Date().getTime().toString(36) + Math.random().toString(36).substring(3);
  localStorage.setItem('uniqueId', device_id);
}
const refer = document.referrer;
export function buryPoint() {
  document.addEventListener('click', (e) => {
    let target = e.target as HTMLElement;
    let event = target.getAttribute('data-event');

    let i = 0;
    while (!event && i < 5 && target.tagName !== 'BODY') {
      target = target.parentNode as HTMLElement;
      if (!target) {
        break;
      }
      event = target.getAttribute('data-event');
      i++;
    }
    let module = target.getAttribute('data-module');

    if (event) {
      while (!module && target.tagName !== 'BODY') {
        target = target.parentNode as HTMLElement;
        if (!target) {
          break;
        }
        module = target.getAttribute('data-module');
      }
    }

    if (module && event) {
      req.post(api.behaviorSave, {
        app: 'pc',
        user_id: store.getState().user.info.uid,
        device_id: device_id,
        module: module,
        event: event,
        page: window.location.pathname,
        page_params: window.location.search.substring(1),
        refer: refer,
        user_agent: navigator.userAgent,
      });
    }
  });
}
